package top.jiaman.javaweb.servlet.user;

import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import top.jiaman.javaweb.dao.UserDAOImpl;
import top.jiaman.javaweb.dao.UserDao;
import top.jiaman.javaweb.entity.BaseResponse;
import top.jiaman.javaweb.entity.User;
import top.jiaman.javaweb.util.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Jiaman
 * @Date 2020/11/28 10:56
 * @Desc
 */

@WebServlet(urlPatterns = "/update/plus")
public class UserUpdatePlusServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        UserDAOImpl uups = UserDAOImpl.getInstance();

        Gson gson = new Gson();
        String userJson = RequestUtil.getRequestBody(req);
        User userBody =  gson.fromJson(userJson, User.class);
        User user = uups.getUserById(String.valueOf(userBody.getId()));
        if ( !StringUtils.isNullOrEmpty(userBody.getName())) {
            user.setName(userBody.getName());
            user.setPassword(userBody.getPassword());
            user.setAddress(userBody.getAddress());
        }

        int i = uups.update(user);

        BaseResponse<Integer> baseResponse = new BaseResponse<Integer>();
        if (i > 0) {
            baseResponse.setCode(200);
            baseResponse.setMsg("操作成功");
            baseResponse.setData(i);
        } else {
            baseResponse.setCode(500);
            baseResponse.setMsg("操作失败");
            baseResponse.setData(i);
        }

        String json = gson.toJson(baseResponse);
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(json);
        writer.flush();
    }
}
